package com.jkc.xh.fragments.core;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.jkc.xh.R;
import com.jkc.xh.views.widget.ErrorView;
import com.jkc.xh.views.widget.ErrorView_;
import com.jkc.xh.views.widget.LoadingView;
import com.jkc.xh.views.widget.LoadingView_;
import com.jkc.xh.views.widget.ProgressDialog;
import com.jkc.xh.views.widget.ProgressDialog_;
import com.umeng.analytics.MobclickAgent;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EFragment;

import java.util.ArrayList;
import java.util.List;

import retrofit.Call;

/**
 * Created by chenliang_91 on 2015/9/17.
 */
@EFragment
public abstract class BaseFragment extends Fragment {

    public static final String FRAGMENT_TAG_KEY = "FRAGMENT_TAG_KEY";

    public static final String FRAGMENT_IS_SECOND = "FRAGMENT_IS_SECOND";

    private static final String FRAGMENT_STACKNAME = "FRAGMENT_STACKNAME";

    public String mLastStackName;


    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getName());
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    public boolean onBackPressed() {
        return false;
    }

    protected ArrayList<Call> mCallArray = new ArrayList<>();

    public void showFragment(BaseFragment fragment) {
        showFragment(fragment, 0, 0);
    }

    public void showFragment(BaseFragment fragment, int animaIn, int animaOut) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.setCustomAnimations(animaIn, 0, 0, animaOut);
        transaction.add(R.id.container, fragment, fragment.getClass().getName());
        fragment.mLastStackName = "" + System.currentTimeMillis() + hashCode();
        transaction.addToBackStack(fragment.mLastStackName);
        transaction.commitAllowingStateLoss();
    }


    private LoadingView mLoadingView;

    protected void showLoading() {
        showLoading((ViewGroup) getView());
    }

    protected void showLoading(int resId) {
        showLoading((ViewGroup) getView().findViewById(resId));
    }

    protected void showLoadingTranslucent(int resId) {
        showLoading((ViewGroup) getView().findViewById(resId), R.color.translucent);
    }

    protected void showLoading(ViewGroup viewParent) {
        if (mLoadingView == null) {
            mLoadingView = LoadingView_.build(getActivity());
        }
        mLoadingView.show(viewParent);
    }

    protected void showLoadingTranslucent() {
        showLoading((ViewGroup) getView(), R.color.translucent);
    }

    protected void showLoading(ViewGroup viewParent, int resId) {
        if (mLoadingView == null) {
            mLoadingView = LoadingView_.build(getActivity());
            mLoadingView.setBackground(resId);
        }
        mLoadingView.show(viewParent);
    }

    protected void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.hide();
        }
    }

    ProgressDialog mProgressDialog;

    protected ProgressDialog showProgress() {
        return showProgress((ViewGroup) getView());
    }


    protected ProgressDialog showProgress(ViewGroup viewParent) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog_.build(getActivity());
            mProgressDialog.addToView(viewParent);
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    protected void hideProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.hide();
        }
    }

    protected void closeProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.removeFromView();
            mProgressDialog = null;
        }
    }


    public void showProgress(@StringRes int msgRes) {
        ProgressDialog dialog = showProgress();
        dialog.setTipMsg(msgRes);
    }

    public void showProgress(String msg) {
        ProgressDialog dialog = showProgress();
        dialog.setTipMsg(msg);
    }


    private ErrorView mErrorPage;

    protected void showError() {
        showError((ViewGroup) getView().getParent());
    }

    protected void showError(int resId) {
        showError((ViewGroup) getView().findViewById(resId));
    }

    protected void showError(ViewGroup viewParent) {
        hideLoading();
        if (mErrorPage == null) {
            mErrorPage = ErrorView_.build(getActivity());
            mErrorPage.setOnClickListener(createErrorPageClickListener());
        }
        if (!mErrorPage.isShown()) {
            if (mErrorPage.getParent() != null) {
                mErrorPage.hide();
            }
            mErrorPage.show(viewParent);
        }
    }

    protected void hideError() {
        if (mErrorPage != null) {
            mErrorPage.hide();
        }
    }

    private View.OnClickListener createErrorPageClickListener() {
        return new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                hideError();
                onErrorClick(v);
            }
        };
    }

    protected void onErrorClick(View view) {
    }

    public void startActivity(Class cls) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        startActivity(intent);
//        getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    public void startFragment(Context context) {

        FragmentActivity fa = scanForFragmentActivity(context);
        if (fa != null) {
            startFragment(fa);
        }
    }

    private static FragmentActivity scanForFragmentActivity(Context cont) {
        if (cont == null)
            return null;
        else if (cont instanceof FragmentActivity)
            return (FragmentActivity) cont;
        else if (cont instanceof ContextWrapper)
            return scanForFragmentActivity(((ContextWrapper) cont).getBaseContext());

        return null;
    }

    public void startFragment(Context context, int animaIn, int animaOut) {
        if (context instanceof FragmentActivity) {
            startFragment((FragmentActivity) context, animaIn, animaOut);
        }
    }

    public void startFragment(Context context, int layoutId) {
        if (context instanceof FragmentActivity) {
            startFragment((FragmentActivity) context, layoutId, null, null);
        }
    }

    public void startFragment(FragmentActivity activity) {
        startFragment(activity, null);
    }

    public void startFragment(FragmentActivity activity, int animaIn, int animaOut) {
        startFragment(activity, R.id.container, null, null, animaIn, animaOut);
    }

    public void startFragment(FragmentActivity activity, String tag) {
        startFragment(activity, null, tag);
    }

    public void startFragment(FragmentActivity activity, String stackName, String tag) {
        startFragment(activity, R.id.container, stackName, tag);
    }

    public void startFragment(FragmentActivity activity, int layoutId, String stackName,
                              String tag) {
        startFragment(activity, layoutId, stackName, tag, 0, 0);
    }

    public void startFragment(FragmentActivity activity, int layoutId, String stackName,
                              String tag, int animaIn, int animaOut) {
        if (!TextUtils.isEmpty(mLastStackName)) {
            this.finishFragment(mLastStackName);
            mLastStackName = null;
        }
        Bundle bundle = getArguments();
        if (bundle == null) {
            bundle = new Bundle();
        }
        if (stackName == null) {
            stackName = "" + System.currentTimeMillis() + hashCode();
        }
        bundle.putString(FRAGMENT_STACKNAME, stackName);
        mLastStackName = stackName;
        if (tag == null) {
            tag = stackName;
        }
        bundle.putString(FRAGMENT_TAG_KEY, tag);
        bundle.putBoolean(FRAGMENT_IS_SECOND, true);
        if (activity != null) {
            setArguments(bundle);
            FragmentTransaction transaction = activity.getSupportFragmentManager()
                    .beginTransaction();
            transaction.addToBackStack(mLastStackName);
            transaction.add(layoutId, this, tag);
            transaction.setCustomAnimations(animaIn, 0, 0, animaOut);
            transaction.addToBackStack(stackName);
            transaction.commitAllowingStateLoss();
            activity.getSupportFragmentManager().executePendingTransactions();
        }
    }


    public void startFragment(FragmentManager fragmentManager, int layoutId) {
        if (!TextUtils.isEmpty(mLastStackName)) {
            this.finishFragment(mLastStackName);
            mLastStackName = null;
        }
        Bundle bundle = getArguments();
        if (bundle == null) {
            bundle = new Bundle();
        }
        String stackName = "" + System.currentTimeMillis() + hashCode();
        bundle.putString(FRAGMENT_STACKNAME, stackName);
        mLastStackName = stackName;
        String tag = stackName;
        bundle.putString(FRAGMENT_TAG_KEY, tag);
        bundle.putBoolean(FRAGMENT_IS_SECOND, true);
        if (fragmentManager != null) {
            setArguments(bundle);
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.addToBackStack(mLastStackName);
            transaction.add(layoutId, this, tag);
            transaction.addToBackStack(stackName);
            transaction.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
    }

    public void finishFragment() {
        finishFragment(mLastStackName);
    }

    public void finishFragment(String name) {

        getFragmentManager().popBackStackImmediate(name,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void finishAboveFragment() {
        getFragmentManager().popBackStackImmediate(mLastStackName, 0);
    }

    public void finishAllFragment() {
        getFragmentManager().popBackStackImmediate(null, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    protected void addJob(Call call) {
        mCallArray.add(call);
    }

    @Background
    protected void clearAllJob() {
        for (Call call : mCallArray) {
            if (call != null) {
                call.cancel();
            }
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        clearAllJob();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setClickable(true);
    }

    @Override
    public void onDestroyView() {
        hideLoading();
        hideError();
        closeProgress();
        super.onDestroyView();
    }


}
